package springbootmybatis.demo.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * IP 工具类
 * 
 * @author Administrator
 *
 */
public class IPUtils {

	/**
	 * 获取 IP
	 * 
	 * @param request
	 *            HttpServletRequest对象
	 * @return String 字符串
	 */
	public static String getIP(HttpServletRequest request) {
		//获取 请求包 头
		String ip = request.getHeader("X-Forwarded-For");
		//非空判断 unKnow判断
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			//多次反向代理后会有多个 IP 值，第一个 IP 才是真实 IP
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		//非空判断 unKnow判断
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}
}
